<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>像素处理</title>
</head>
<body>
  <canvas id="paper" width="0" height="0"></canvas>
  <script type="module">
    import {loadImage, getImageData, traverse} from './lib/util.js';
    import {transformColor} from './lib/color-matrix.js';

    function brightness(p) {
      return [
        p, 0, 0, 0, 0,
        0, p, 0, 0, 0,
        0, 0, p, 0, 0,
        0, 0, 0, 1, 0,
      ];
    }

    function saturate(p) {
      const r = 0.212 * (1 - p);
      const g = 0.714 * (1 - p);
      const b = 0.074 * (1 - p);
      return [
        r + p, g, b, 0, 0,
        r, g + p, b, 0, 0,
        r, g, b + p, 0, 0,
        0, 0, 0, 1, 0,
      ];
    }

    function grayscale(p) {
      const r = 0.212 * p;
      const g = 0.714 * p;
      const b = 0.074 * p;

      return [
        r + 1 - p, g, b, 0, 0,
        r, g + 1 - p, b, 0, 0,
        r, g, b + 1 - p, 0, 0,
        0, 0, 0, 1, 0,
      ];
    }

    function channel({r = 1, g = 1, b = 1}) {
      return [
        r, 0, 0, 0, 0,
        0, g, 0, 0, 0,
        0, 0, b, 0, 0,
        0, 0, 0, 1, 0,
      ];
    }

    const canvas = document.getElementById('paper');
    const context = canvas.getContext('2d');

    (async function () {
      const img = await loadImage('assets/girl1.jpg');
      const imageData = getImageData(img);

      traverse(imageData, ({r, g, b, a}) => {
        return transformColor(
          [r, g, b, a],
          channel({r: 1.2}),
          brightness(1.2),
          saturate(1.2),
        );
      });

      canvas.width = imageData.width;
      canvas.height = imageData.height;
      context.putImageData(imageData, 0, 0);
    }());
  </script>
</body>
</html>